package com.yys.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.yys.common.to.mq.OrderTo;
import com.yys.common.to.user.MemberVo;
import com.yys.common.utils.R;
import com.yys.gulimall.order.constant.OrderConstant;
import com.yys.gulimall.order.entity.OrderItemEntity;
import com.yys.gulimall.order.entity.PaymentInfoEntity;
import com.yys.gulimall.order.enume.OrderStatusEnum;
import com.yys.gulimall.order.feign.CartFeignService;
import com.yys.gulimall.order.feign.MemberFeignService;
import com.yys.gulimall.order.feign.ProductFeignService;
import com.yys.gulimall.order.feign.WareFeignService;
import com.yys.gulimall.order.interceptor.LoginUserInterceptor;
import com.yys.gulimall.order.service.OrderItemService;
import com.yys.gulimall.order.service.PaymentInfoService;
import com.yys.gulimall.order.to.OrderCreateTo;
import com.yys.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yys.common.utils.PageUtils;
import com.yys.common.utils.Query;

import com.yys.gulimall.order.dao.OrderDao;
import com.yys.gulimall.order.entity.OrderEntity;
import com.yys.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import static com.yys.common.constant.OrderConstant.ORDER_STATUS_CLOSE;
import static com.yys.common.constant.OrderConstant.ORDER_STATUS_CREATE;
import static com.yys.gulimall.order.constant.OrderConstant.ORDER_CREATE_ROUTING_KEY;
import static com.yys.gulimall.order.constant.OrderConstant.ORDER_EVENT_EXCHANGE;
import static com.yys.gulimall.order.constant.OrderConstant.ORDER_RELEASE_OHTER_ROUTING_KEY;
import static com.yys.gulimall.order.constant.PayedConstant.TRADE_FINISHED;
import static com.yys.gulimall.order.constant.PayedConstant.TRADE_SUCCESS;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ProductFeignService productFeignService;


    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;



    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberVo memberVo = LoginUserInterceptor.threadLocal.get();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        /*
         远程查询地址
         远程查询购物项
         这里要带上登录信息才行,需要封装头信息
         feign 远程调用会构造请求会用拦截器进行增强,我们使用拦截器加上请求头
         注意异步调用会开启新线程而上下文放入了threadLocal中这样会获取不到上下文,可以给每一个线程在放一份
        */
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberVo.getId());
            orderConfirmVo.setAddress(address);
        }, threadPoolExecutor);

        CompletableFuture<Void> confirmFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> orderItemVos = cartFeignService.getCurrentUserCartItems();
            orderConfirmVo.setOrderItemVos(orderItemVos);
        },threadPoolExecutor).thenRunAsync(()->{
            // 查询库存信息
            List<OrderItemVo> orderItemVos = orderConfirmVo.getOrderItemVos();
            List<Long> skuIds = orderItemVos.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasStock(skuIds);
            List<SkuHasStockTo> skuHasStockTos = r.getData(new TypeReference<List<SkuHasStockTo>>() {});
            if(ObjectUtils.isNotEmpty(skuHasStockTos)){
                Map<Long, Boolean> stocks = skuHasStockTos.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
                orderConfirmVo.setStocks(stocks);
            }
        },threadPoolExecutor);
        // 查询用户积分
        Integer integration = memberVo.getIntegration();

        orderConfirmVo.setIntegration(integration);

        CompletableFuture.allOf(addressFuture,confirmFuture).get();

        //TODO 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);
        return orderConfirmVo;
    }

    @Override
    @Transactional
    // 使用seata分布式事务
//    @GlobalTransactional
    public OrderSubmitRespVo submitOrder(OrderSubmitVo orderSubmitVo) {
        OrderSubmitRespVo orderSubmitRespVo = new OrderSubmitRespVo();
        MemberVo memberVo = LoginUserInterceptor.threadLocal.get();
        orderSubmitVoThreadLocal.set(orderSubmitVo);
        orderSubmitRespVo.setCode(0);
        // 创建订单 验证令牌
        //验证令牌
        String orderToken = orderSubmitVo.getOrderToken();

//        String token = stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId());
        //这里需要保证原子性
//        if(StringUtils.isNotBlank(orderToken) && orderToken.equals(token)) {
//            // 验证通过删除令牌
//        }
        // 返回0/1 失败返回0(值不存在或删除失败)
        String lua = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String key = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId();
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<>(lua, Long.class), Collections.singletonList(key), orderToken);
        if(result != null && result == 1) {
            // 创建订单
            OrderCreateTo order = createOrder();
            // 验价格
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            BigDecimal abs = payAmount.subtract(payPrice).abs();
            if(abs.doubleValue() < 0.01) {
                // 保存订单
                saveOrder(order);
                // 锁定库存,只要有异常回滚订单数据
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    orderItemVo.setPrice(item.getSkuPrice());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItemVos);
                //TODO 远程锁库存
                // 解决方案1 . 失败给库存发送一条消息让库存自己处理回滚
                // 2. 库存可以自动解锁
                R r = wareFeignService.orderLock(wareSkuLockVo);
                if(r.getCode() == 0) {
                    // 订单创建成功 TODO 发送消息给mq
                    rabbitTemplate.convertAndSend(
                            ORDER_EVENT_EXCHANGE,
                            ORDER_CREATE_ROUTING_KEY,
                            order.getOrder()
                    );
                    orderSubmitRespVo.setOrder(order.getOrder());
                } else {
                    // 锁定失败
                    orderSubmitRespVo.setCode(3);
                    throw new RuntimeException("库存锁定失败");
                }
            } else {
                // 金额对比失败
                orderSubmitRespVo.setCode(2);
            }
        } else {
            // 验证失败
            orderSubmitRespVo.setCode(1);
        }
        return orderSubmitRespVo;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        // 查询订单状态
        OrderEntity order = this.getById(orderEntity);
        if(ObjectUtils.isNotNull(order) && order.getStatus() == ORDER_STATUS_CREATE){
            OrderEntity updateOrder = new OrderEntity();
            updateOrder.setId(order.getId());
            updateOrder.setStatus(ORDER_STATUS_CLOSE);
            this.updateById(updateOrder);
            // 给mq发送消息主动解锁库存
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);

            try{
                //TODO 保证消息一定发送成功
                rabbitTemplate.convertAndSend(
                        ORDER_EVENT_EXCHANGE,
                        ORDER_RELEASE_OHTER_ROUTING_KEY,
                        orderTo
                );
            } catch (Exception e) {
                // TODO 重试 记录一张日志表(给数据库保存数据) 定期扫描数据库将失败的数据再发一遍
            }
        }
    }

    @Override
    public PayVo getorderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
        payVo.setOut_trade_no(orderEntity.getOrderSn()); // 商户订单号 必填
        payVo.setSubject("订单 " + orderEntity.getOrderSn() + " 号订单收银台"); // 订单名称 必填

        BigDecimal payAmount = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString());  // 付款金额 必填

        payVo.setBody("注意此商品为非卖品,请联系商家"); // 商品描述 可空
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberVo memberVo = LoginUserInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                .eq("member_id",memberVo.getId())
                .orderByDesc("id")
        );

        List<OrderEntity> orderEntities = page.getRecords().stream().peek(item -> {
            List<OrderItemEntity> orderItemEntities =
                    orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", item.getOrderSn()));
            item.setOrderItemEntities(orderItemEntities);
        }).collect(Collectors.toList());

        page.setRecords(orderEntities);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo payAsyncVo) {
        // 保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfoEntity.setCallbackTime(payAsyncVo.getNotify_time());

        paymentInfoService.save(paymentInfoEntity);

        // 支付成功修改订单状态
        if (
                payAsyncVo.getTrade_status().equalsIgnoreCase(TRADE_SUCCESS) ||
                payAsyncVo.getTrade_status().equalsIgnoreCase(TRADE_FINISHED)
        ) {

            String orderSn = payAsyncVo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode());
        }

        return "success";
    }

    /**
     * 保存订单
     * @param order 订单
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        orderEntity.setCreateTime(new Date());
        orderService.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);

        // 获取所有订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);

        // 验价格
        computePrice(orderEntity,orderItemEntities);

        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);

        return orderCreateTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        // 订单价格计算
        BigDecimal totalPrice = new BigDecimal("0.0");
        BigDecimal totalCoupon = new BigDecimal("0.0");
        BigDecimal totalIntegration = new BigDecimal("0.0");
        BigDecimal totalPromotion = new BigDecimal("0.0");
        BigDecimal totalGift = new BigDecimal("0.0");
        BigDecimal totalGiftGrowth = new BigDecimal("0.0");

        if(ObjectUtils.isNotEmpty(orderItemEntities)) {
            for (OrderItemEntity orderItemEntity : orderItemEntities) {
                BigDecimal realAmount = orderItemEntity.getRealAmount();
                totalPrice = totalPrice.add(realAmount);

                BigDecimal couponAmount = orderItemEntity.getCouponAmount();
                totalCoupon = totalCoupon.add(couponAmount);

                BigDecimal integrationAmount = orderItemEntity.getIntegrationAmount();
                totalIntegration = totalIntegration.add(integrationAmount);

                BigDecimal promotionAmount = orderItemEntity.getPromotionAmount();
                totalPromotion = totalPromotion.add(promotionAmount);

                BigDecimal giftIntegration = new BigDecimal(orderItemEntity.getGiftIntegration().toString());
                totalGift = totalGift.add(giftIntegration);

                BigDecimal giftGrowth = new BigDecimal(orderItemEntity.getGiftGrowth().toString());
                totalGiftGrowth = totalGiftGrowth.add(giftGrowth);

            }
        }

        //设置价格相关
        orderEntity.setTotalAmount(totalPrice);
        orderEntity.setPayAmount(totalPrice.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(totalPromotion);
        orderEntity.setIntegrationAmount(totalIntegration);
        orderEntity.setCouponAmount(totalCoupon);

        // 设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        // 自动确认时间
        orderEntity.setAutoConfirmDay(OrderConstant.AUTO_CONFIRM_DAY);

        // 设置积分
        orderEntity.setGrowth(totalGiftGrowth.intValue());
        orderEntity.setIntegration(totalGift.intValue());

        // 删除状态
        orderEntity.setDeleteStatus(OrderConstant.DELETE_STATUS);

    }

    /**
     * @param orderSn 订单号
     * @return 创建订单
     */
    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        MemberVo memberVo = LoginUserInterceptor.threadLocal.get();
        orderEntity.setMemberId(memberVo.getId());
        // 获取收货地址信息
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();
        //TODO 收货地址还没有
        R r = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = r.getData(new TypeReference<FareVo>() {});
        // 设置运费金额
        orderEntity.setFreightAmount(fareVo.getFare());
        // 设置其他信息
        BeanUtils.copyProperties(fareVo.getAddress(),orderEntity);
        return orderEntity;
    }


    /**
     * @param orderSn 订单号
     * @return 构建所有订单的订单项
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 最后确定购物项的价格 --> 购买商品的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if(ObjectUtils.isNotEmpty(currentUserCartItems)) {
            return currentUserCartItems.stream().map(item->{
                OrderItemEntity orderItemEntity = buildOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * @param item 订单vo
     * @return 构建一个订单项
     */
    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 订单信息 spu
        Long skuId = item.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = r.getData( new TypeReference<SpuInfoVo>() {});
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        // sku
        orderItemEntity.setSkuId(item.getSkuId());
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuPic(item.getImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(item.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(item.getCount());
        // 优惠...
        // 积分
        orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());

        //订单项价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        // 当前订单项的实际金额
        BigDecimal realPrice = orderItemEntity.getSkuPrice()
                .multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()))
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realPrice);
        return orderItemEntity;
    }

}